const fs = require('fs');
const path = require('path');

const regStyle = /<style>[\s\S]*<\/style>/;

const regScript = /<script>[\s\S]*<\/script>/;

function resolveCSS(htmlStr) {
    const r1 = regStyle.exec(htmlStr);
    const newCSS = r1[0].replace('<style>','').replace('</style>','');
    fs.writeFile(path.join(__dirname,'./clock/index.css'),newCSS,function(err) {
        if (err) {
            return console.log('写入css样式失败' + err.message);
        }    
        console.log('写入css样式成功');
    })
}

function resolveScript(htmlStr) {
    const r2 = regScript.exec(htmlStr);
    const newJS = r2[0].replace('<script>','').replace('</script>','');
    fs.writeFile(path.join(__dirname,'./clock/index.js'),newJS,function(err) {
        if (err) {
            return console.log('写入js失败' + err.message);
        }    
        console.log('写入js成功');
    })
}

function resolveHTML(htmlStr) {
    const newHTML = htmlStr.replace(regStyle,'<link rel = "stylesheet" href = "./index.css"/>').replace(regScript,'<script src = "./index.js"></script>');
    fs.writeFile(path.join(__dirname,'./clock/index.html'),newHTML,function(err) {
        if (err) {
            return console.log('写入HTML文件失败' + err.message);
        }    
        console.log('写入HTML文件成功');
    })
}

fs.readFile(path.join(__dirname,'./index.html'),'utf8',function(err,dataStr){
    if (err) {
        return console.log('信息读取失败' + err.message);
    }

    resolveCSS(dataStr);
    resolveScript(dataStr);
    resolveHTML(dataStr);
})

